﻿(function(window) {
	
	/////////////////////////////////////
	////	Constants
	//
	var DEFAULT_FPS = 15;
	
	/* ******************************** */
	var SpriteMovie = function(url, frameWidth, frameHeight, cols, rows, fps) {
		
		if(isNaN(fps))
			fps = SpriteMovie.DEFAULT_FPS;
		
		var el = ix.make('div');
		
		el.cols = cols;
		el.rows = rows;
		el.loop = true;
		el.col = 0;
		el.row = 0;
		
		el.style.display = 'inline-block';
		el.style.width = frameWidth + 'px';
		el.style.height = frameHeight + 'px';
		el.style.backgroundImage = 'url("' + url + '")';
		
		var timer = 0;
		var debug = false;
		
/* Public **/
		
		el.play = function(dbg) {
			if(el.isPlaying())
				return;
			debug = dbg;
			if(debug)
			ix.log('SpriteMovie::play(): playing "' + el.className + '" @ ' + fps + ' fps:'+
					' frame=' + el.col + 'x' + el.row);
			timer = setInterval(nextFrame, 1000 / fps);
			el.gotoFrame(el.col, el.row);
		};
		
		el.stop = function() {
			if(!el.isPlaying())
				return;
			clearInterval(timer);
			timer = 0;
			if(el.onStop && typeof(el.onStop) == 'function') {
				var event = {
					'type': 'stop',
					'currentTarget': el
				};
				el.onStop(event);
			}
		};
		
		el.isPlaying = function() {
			return timer > 0;
		};
		
/* Private  **/
		
		var nextFrame = function() {
			if(++el.col >= el.cols) {
				if(!el.loop) {
					el.stop();
					return;
				}
				el.col = 0;
			}
			el.gotoFrame(el.col, el.row);
		};
		
		el.gotoFrame = function(x, y) {
			var xx = -x % el.cols;
			var yy = -y % el.rows;
			el.col = x;
			el.row = y;
			el.style.backgroundPosition = (xx * frameWidth) + 'px ' + (yy * frameHeight) + 'px';
			if(debug)
			ix.log('SpriteMovie::gotoFrame(' + getTimer() + '): '+
					'"' + el.className + '" @ ' + el.col + '/' + el.cols + ' x ' + el.row + '/' + el.rows);
		};
		
		return el;
	};
	
	/* E o F ***************************************/
	
	SpriteMovie.DEFAULT_FPS = DEFAULT_FPS;
	
	window.SpriteMovie = SpriteMovie;
	
}(window))
